// https://leetcode.cn/problems/print-foobar-alternately/
// Created by ade on 2022/11/2.
// 两个线程A和B，分别交替打印foo和bar

class FooBar {
private:
    int n;
    atomic<bool> flag;

public:
    FooBar(int n) {
        this->n = n;
        flag = true;
    }

    void foo(function<void()> printFoo) {
        for (int i = 0; i < n; i++) {
            while (!flag) this_thread::yield(); // 当前线程让出cpu时间片

            // printFoo() outputs "foo". Do not change or remove this line.
            printFoo();
            flag = false;
        }
    }

    void bar(function<void()> printBar) {
        for (int i = 0; i < n; i++) {
            while (flag) this_thread::yield();
            // printBar() outputs "bar". Do not change or remove this line.
            printBar();
            flag = true;
        }
    }
};